import React,{useEffect} from 'react'
import {useDispatch,useSelector} from 'react-redux'
import {getShopcartListAsync,changNumAsync,changInputNumAsync,checkedProductAsync} from '../store/async/shopcartAsync'
import '../assets/shopcart.scss'
export default function ShopCart() {



  const dispatch=useDispatch()
  const list=useSelector((state)=>{
    
    return state.shopcart.shopcartList
  })
  useEffect(()=>{
    dispatch(getShopcartListAsync)
  },[])

  const changeNum=(arg)=>{
    dispatch(changNumAsync(arg))
  }
  const changeInputNum=(arg)=>{
    dispatch(changInputNumAsync(arg))
  }
  const checkedProduct=(_id)=>{
    dispatch(checkedProductAsync(_id))
  }
  return (
    <div>
        <table>
          <thead>
            <tr>
              <td>序号</td>
              <td>名称</td>
              <td>单价</td>
              <td>数量</td>
              <td>小计</td>
            </tr>
          </thead>
          <tbody>
            {
              list.map(item=><tr key={item._id}>
                <td>
                  <input type="checkbox" checked={item.checked} onChange={()=>checkedProduct(item._id)}/>
                </td>
                <td>{item.name}</td>
                <td>{item.price}</td>
                <td>
                <button className='changeNumBtn' onClick={()=>changeNum({_id:item._id,n:-1})}>-</button>
                  <span>
                    <input type="text" value={item.num} className="inputNum" onChange={(e)=>changeInputNum({_id:item._id,n:e.target.value})}/>
                  </span>
                  <button className='changeNumBtn' onClick={()=>changeNum({_id:item._id,n:1})}>+</button>
                </td>
                <td>{(item.price*item.num).toFixed(0)}</td>
              </tr>)
            }
          </tbody>
        </table>
    </div>
  )
}
